package com.away.transaction;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

@Component
@RocketMQTransactionListener(txProducerGroup = "transactionGroup")
public class OrderTransactionListener implements RocketMQLocalTransactionListener {

    /**
     * 执行本地事务
     * @param msg
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        MessageHeaders headers = msg.getHeaders();
        Object orderId = headers.get("orderId");
        Object orderInfo = headers.get("orderInfo");
        //消息为空直接回滚
        if(orderId==null||orderInfo == null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //开启本地事务
        try {
            boolean save = OrderDB.save((String)orderId,(String) orderInfo);
//            提交事务
            if(save){
                return RocketMQLocalTransactionState.COMMIT;
            }else{
                return RocketMQLocalTransactionState.ROLLBACK;
            }
        }catch (Exception e){
            return RocketMQLocalTransactionState.ROLLBACK;

        }

    }

    /**
     *
     * @param msg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        MessageHeaders headers = msg.getHeaders();
        Object orderId = headers.get("orderId");
        //这个消息有问题，直接返回
        if(orderId==null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }

        //当数据库消息已经存在时，直接将消息commit
        if (OrderDB.exist(orderId.toString())) {
            return RocketMQLocalTransactionState.COMMIT;
        }else{//数据库消息还未存在，则返回UNKNOW 等待消息broker继续回调查询
            return RocketMQLocalTransactionState.UNKNOWN;

        }
    }
}
